package com.hyzs.service.impl;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.hyzs.service.RawDataService;
import com.hyzs.utils.MySQLConnectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MySQLDataService implements RawDataService {

    @Autowired
    MySQLConnectionUtils  connectionUtils;

    @Override
    public Map<String, Object> getJudgementContentById(String doc_id) {
        Connection connection = null;
        try {
            connection = connectionUtils.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String sql = " SELECT doc_id, content, html_content FROM judicial_document WHERE doc_id = ? ";
        Map<String, Object> prop = new HashMap<>();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, doc_id);
            ResultSet resultSet = preparedStatement.executeQuery();
            resultSet.next();
            prop.put("doc_id", resultSet.getString(1));
            prop.put("content", resultSet.getString(2));
            prop.put("html_content", resultSet.getString(3));
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return prop;
    }

    @Override
    public List<Map<String, Object>> getJudgementContentByIds(List<String> doc_ids) {
        Connection connection = null;
        try {
            connection = connectionUtils.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String idsStr = doc_ids.stream().map(id -> "'" + id + "'")
                .collect(Collectors.joining(","));
        String sql = " SELECT doc_id, content, html_content FROM judicial_document WHERE doc_id IN ("+idsStr+") ";
        List<Map<String, Object>> resList = new ArrayList<>();
        try {
            Statement statement  = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            while(resultSet.next()){
                Map<String, Object> prop = new HashMap<>();
                prop.put("doc_id", resultSet.getString(1));
                prop.put("content", resultSet.getString(2));
                prop.put("html_content", resultSet.getString(3));
                resList.add(prop);
            }

            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resList;
    }
}
